#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
闲云潭影日悠悠, 物换星移几度秋!
						--王勃
"""
from pyse import Pyse
from time import sleep

CSS_SUBMIT = "id=>J_SubmitQuick"
CSS_USER_FORMAT = "css=>#J_QuickLogin > form > ul.ww-userlist > li:nth-child(%s) > label"
URL = "https://oauth.taobao.com/authorize?response_type=token&client_id=23398461&state=bkx&view=web"

def parseToken(url):
	if 'access_token=' in url:
		return url.split('access_token=')[1].split('&')[0]
	else:
		return None

def getAlimamaSessionAccessToken(user):
	driver = Pyse("ie")
	driver.open(URL)
	
	driver.element_wait("css", "#J_loginIframe", 5)
	
	url = driver.get_attribute("css=>#J_loginIframe", 'src')
	driver.open(url)

	driver.element_wait("css", "#J_QuickLogin", 5)

	n = 1
	token = None
	while True:
		try:
			text = driver.get_text(CSS_USER_FORMAT % n)
			if text == user:
				driver.click( CSS_USER_FORMAT % n )
				driver.submit(CSS_SUBMIT)
				sleep(3)
				token = parseToken(driver.get_url())
				if not token:
					driver.F5()
					driver.click( CSS_USER_FORMAT % n )
					driver.submit(CSS_SUBMIT)
					sleep(3)
					token = parseToken(driver.get_url())
				break
			n += 1
		except Exception as e:
			break
	driver.close()
	return token

if __name__ == '__main__':
	user = u'xmyandayu'
	fileName = ('%s_cookies.txt' % user).encode('gbk')
	main(user)